<template>
    <div class="request-section">
        <!-- 接口名称输入 -->
        <div class="api-name-line">
            <n-input v-model:value="apiName" placeholder="请输入接口名称" class="api-name-input" />
            <n-button @click="handleSave" :disabled="!url">
                保存接口
            </n-button>
        </div>
        <!-- 请求区域 -->
        <div class="request-line">
            <n-select v-model:value="requestMethod" :options="methodOptions" style="width: 100px" />
            <n-input v-model:value="url" placeholder="请输入请求地址" class="url-input" />
            <n-button type="primary" @click="sendRequest" :loading="loading">
                发送请求
            </n-button>
        </div>
        <!-- 参数配置区域 -->
        <n-tabs type="line" class="request-params">
            <n-tab-pane name="headers" tab="Headers">
                <div class="params-container">
                    <div v-for="(item, index) in headers" :key="index" class="param-item">
                        <n-input v-model:value="item.key" placeholder="Header名称" />
                        <n-input v-model:value="item.value" placeholder="Header值" />
                        <n-button quaternary circle type="error" @click="removeHeader(index)">
                            ×
                        </n-button>
                    </div>
                    <n-button dashed class="add-btn" @click="addHeader">
                        添加 Header
                    </n-button>
                </div>
            </n-tab-pane>

            <n-tab-pane name="query" tab="Query Params">
                <div class="params-container">
                    <div v-for="(item, index) in queryParams" :key="index" class="param-item">
                        <n-input v-model:value="item.key" placeholder="参数名" />
                        <n-input v-model:value="item.value" placeholder="参数值" />
                        <n-button quaternary circle type="error" @click="removeQuery(index)">
                            ×
                        </n-button>
                    </div>
                    <n-button dashed class="add-btn" @click="addQuery">
                        添加参数
                    </n-button>
                </div>
            </n-tab-pane>

            <n-tab-pane name="body" tab="Body">
                <div class="body-type-select">
                    <n-select v-model:value="bodyType" :options="bodyTypeOptions" style="width: 200px" />
                </div>
                <div class="body-content" v-if="bodyType !== 'none'">
                    <template v-if="bodyType === 'form-data'">
                        <n-dynamic-input v-model:value="formData" :on-create="onCreate" key-placeholder="参数名"
                            value-placeholder="参数值">
                            <template #create-button-default>
                                添加表单项
                            </template>
                        </n-dynamic-input>
                    </template>

                    <template v-else-if="bodyType === 'raw'">
                        <n-input v-model:value="rawBody" type="textarea" placeholder="请输入Raw数据" :rows="8" />
                    </template>
                </div>
            </n-tab-pane>
        </n-tabs>

        <!-- 响应区域 -->
        <div class="response-section">
            <div class="response-header">
                <span>Response</span>
                <span v-if="responseTime" class="response-time">
                    {{ responseTime }}ms
                </span>
            </div>
            <div class="response-body">
                <n-scrollbar>
                    <n-input v-model:value="formattedResponse" type="textarea" :autosize="{ minRows: 10, maxRows: 10 }"
                        placeholder="" readonly />
                </n-scrollbar>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import axios from 'axios'
import view from '@renderer/util/ui/ViewUtil'

// Props 定义
const props = defineProps<{
    selectedRequest?: any
}>()

// Emits 定义
const emit = defineEmits<{
    (e: 'save', data: any): void
}>()

// 请求方法选项
const methodOptions = [
    { label: 'GET', value: 'GET' },
    { label: 'POST', value: 'POST' },
    { label: 'PUT', value: 'PUT' },
    { label: 'DELETE', value: 'DELETE' },
    { label: 'PATCH', value: 'PATCH' }
]

// body类型选项
const bodyTypeOptions = [
    { label: 'none', value: 'none' },
    { label: 'form-data', value: 'form-data' },
    { label: 'raw', value: 'raw' }
]

// 请求相关的响应式数据
const apiName = ref('')
const requestMethod = ref('GET')
const url = ref('')
const headers = ref<Array<{ key: string, value: string }>>([])
const queryParams = ref<Array<{ key: string, value: string }>>([])
const bodyType = ref('none')
const formData = ref([])
const rawBody = ref('')

// 响应数据
const response = ref<any>(null)
const responseTime = ref<number>(0)
const loading = ref(false)

// Headers 相关方法
const addHeader = () => {
    headers.value.push({ key: '', value: '' })
}

const removeHeader = (index: number) => {
    headers.value.splice(index, 1)
}

// Query params 相关方法
const addQuery = () => {
    queryParams.value.push({ key: '', value: '' })
}

const removeQuery = (index: number) => {
    queryParams.value.splice(index, 1)
}

// 发送请求
const sendRequest = async () => {
    if (!url.value) {
        view.alertErrorMessage('请输入请求地址')
        return
    }

    loading.value = true
    const startTime = Date.now()

    try {
        // 处理headers
        const headerObj = {}
        headers.value.forEach(item => {
            if (item.key) {
                headerObj[item.key] = item.value
            }
        })

        // 处理query参数
        const queryObj = {}
        queryParams.value.forEach(item => {
            if (item.key) {
                queryObj[item.key] = item.value
            }
        })

        // 处理body数据
        let data = null
        if (bodyType.value === 'form-data') {
            const formDataObj = new FormData()
            formData.value.forEach(item => {
                if (item.key) {
                    formDataObj.append(item.key, item.value)
                }
            })
            data = formDataObj
        } else if (bodyType.value === 'raw') {
            try {
                data = JSON.parse(rawBody.value)
            } catch {
                data = rawBody.value
            }
        }

        // 使用主进程代理发送请求
        const result = await window.electron.ipcRenderer.invoke('proxy-http-request', {
            method: requestMethod.value,
            url: url.value,
            headers: headerObj,
            params: queryObj,
            data: data
        })

        if (result.success) {
            response.value = result.data
            responseTime.value = Date.now() - startTime
        } else {
            throw result.error
        }
    } catch (error) {
        response.value = {
            error: error.message,
            ...(error.response || {})
        }
    } finally {
        loading.value = false
    }
}

// 格式化响应数据
const formattedResponse = computed(() => {
    if (!response.value) return ''
    try {
        return JSON.stringify(response.value, null, 2)
    } catch (e) {
        return String(response.value)
    }
})

// 保存请求
const handleSave = () => {
    if (!url.value) {
        view.alertErrorMessage('请输入请求地址')
        return
    }

    const requestData = {
        name: apiName.value,
        method: requestMethod.value,
        url: url.value,
        headers: headers.value.map(h => ({ ...h })),
        queryParams: queryParams.value.map(q => ({ ...q })),
        bodyType: bodyType.value,
        formData: formData.value.map(f => ({
            key: f.key || '',
            value: f.value || ''
        })),
        rawBody: rawBody.value,
        createdAt: new Date().toISOString()
    }

    emit('save', requestData)
}

// 加载请求数据
const loadRequest = (request: any) => {
    if (!request) {
        requestMethod.value = 'GET'
        apiName.value = ''
        url.value = ''
        headers.value = []
        queryParams.value = []
        bodyType.value = 'none'
        formData.value = []
        rawBody.value = ''
        return
    }

    apiName.value = request.name
    requestMethod.value = request.method
    url.value = request.url
    headers.value = request.headers
    queryParams.value = request.queryParams
    bodyType.value = request.bodyType
    formData.value = request.formData || []
    rawBody.value = request.rawBody || ''
}

// 监听 selectedRequest 变化
watch(() => props.selectedRequest, (newRequest) => {
    loadRequest(newRequest)
}, { immediate: true })

// 处理快捷键保存
const handleKeyDown = (e: KeyboardEvent) => {
    // 检查是否按下 Ctrl+S 或 Command+S
    if ((e.ctrlKey || e.metaKey) && e.key === 's') {
        e.preventDefault() // 阻止默认的保存行为
        handleSave() // 调用已有的保存方法
    }
}

// 组件挂载时添加事件监听
onMounted(() => {
    document.addEventListener('keydown', handleKeyDown)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
    document.removeEventListener('keydown', handleKeyDown)
})
</script>

<style scoped>
.request-panel {
    height: 100%;
    display: flex;
    flex-direction: column;
    gap: 16px;
    overflow: auto;
}

/* 请求区域样式 */
.api-name-line {
    display: flex;
    gap: 8px;
    align-items: center;
}

.api-name-input {
    flex: 1;
}

.request-line {
    display: flex;
    gap: 8px;
    align-items: center;
}

.url-input {
    flex: 1;
}

.request-params {
    flex: 0 0 auto;
    min-height: 100px;
    max-height: 250px;
    overflow: auto;
}

.params-container {
    display: flex;
    flex-direction: column;
    gap: 8px;
    padding: 16px;
}

.param-item {
    display: flex;
    gap: 8px;
    align-items: center;
}

.param-item .n-input {
    flex: 1;
}

.add-btn {
    margin-top: 8px;
    width: 100%;
}

.body-type-select {
    margin-bottom: 16px;
}

/* 响应区域样式 */
.response-section {
    flex: 1;
    min-height: 0;
    overflow: auto;
}

.response-header {
    flex: 0 0 auto;
    padding: 8px 16px;
    border-bottom: 1px solid var(--border-color);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.response-time {
    color: var(--text-color-3);
    font-size: 0.9em;
}

.response-body {
    flex: 1;
    padding: 12px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
}

.response-body :deep(.n-scrollbar) {
    flex: 1;
    min-height: 0;
}

.response-body :deep(.n-input) {
    height: 100%;
}

.response-body :deep(.n-input__textarea) {
    font-family: monospace;
}

.response-body :deep(.n-input__textarea-el) {
    white-space: pre-wrap !important;
    min-height: 350px !important;
    word-break: break-all !important;
    word-wrap: break-word !important;
}
</style>